package com.pretty.test.controller.system.upload;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileUploadController {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    public final static String PROJECT_POSITION = "C:/for_graduate/pet-angular2/";
    public final static String UPLOAD_PATH_PREFIX = "upload";
    @RequestMapping("/upload")
    public Map<String, String> upload(@RequestParam("upload_file") MultipartFile file) {
        String path = PROJECT_POSITION + UPLOAD_PATH_PREFIX; // 文件保存路径
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String name = fileName.substring(0, fileName.lastIndexOf("."));
        String id = String.valueOf(new Date().getTime());
        String saveFileName = id + "-" + name + "." + fileExtensionName;
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile = new File(path, saveFileName);
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, String> result = new HashMap<>();
        result.put("url", UPLOAD_PATH_PREFIX + "/" + saveFileName);
        result.put("uid", id);
        result.put("name", fileName);
        return result;
    }

}
